/*
 * @Description: 公共工具
 * @Author: HuiSir<273250950@qq.com>
 * @Date: 2021-09-16 18:50:17
 * @LastEditTime: 2025-09-29 10:07:59
 */

/* eslint-disable */

/**
 * 复制到剪贴板
 */
export const copy2Clipboard = (str: string) => {
  return new Promise((resolve, reject) => {
    const input = document.createElement("input");
    document.body.appendChild(input);
    input.value = str; // 复制到剪切板的内容
    input.select();
    if (document.execCommand) {
      document.execCommand("copy");
      input.remove();
      resolve(true);
    } else {
      input.remove();
      reject("当前浏览器不支持拷贝！");
    }
  });
};

/**
 * JSON转FormData
 * 参数2 可传已有的FormData对象用于合并
 * 此方法支持多层嵌套，数组会被转换为 key[index] 格式（如 user.hobbies[0]）
 */
export const JsonToFormData = (
  data: any[] | Record<string, any>,
  form = new FormData(),
  parentKey = ""
) => {
  if (data === null || data === undefined) {
    form.append(parentKey, "");
    return;
  }

  if (Array.isArray(data)) {
    data.forEach((item, index) => {
      const key = parentKey ? `${parentKey}[${index}]` : index;
      JsonToFormData(item, form, String(key));
    });
  } else if (typeof data === "object") {
    Object.keys(data).forEach((key) => {
      const newKey = parentKey ? `${parentKey}.${key}` : key;
      JsonToFormData(data[key], form, newKey);
    });
  } else {
    form.append(parentKey, data);
  }
  return form;
};

/**
 * 使用图片blob对象异步获取图片信息
 */
export const getImageInfoByFile = (
  file: Blob | MediaSource
): Promise<HTMLImageElement> => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = URL.createObjectURL(file);
    img.onload = () => {
      resolve(img);
      URL.revokeObjectURL(img.src); // 释放内存
    };
    img.onerror = () => reject("图片加载失败");
  });
};

/**
 * 字段映射
 */
export const fieldMapping = ({
  data,
  fieldsMap,
  reverse = false,
}: {
  /**
   * 需要更改字段的对象
   */
  data?: Recordable;
  /**
   * 字段映射
   */
  fieldsMap: Recordable<string>;
  /**
   * 是否反向操作（反向用于传参，正向用于结果数据调整）
   */
  reverse?: boolean;
}) => {
  Object.keys(fieldsMap).forEach((leftKey) => {
    const rightKey = fieldsMap[leftKey];
    if (
      data &&
      reverse &&
      Object.prototype.hasOwnProperty.call(data, leftKey) &&
      leftKey !== rightKey
    ) {
      data[rightKey] = data[leftKey];
      delete data[leftKey];
    } else if (
      data &&
      Object.prototype.hasOwnProperty.call(data, rightKey) &&
      leftKey !== rightKey
    ) {
      data[leftKey] = data[rightKey];
      delete data[rightKey];
    }
  });
};

/**
 * 已知选项和值，取名称
 */
export const getOptLabel = (options: Option[], value: unknown) => {
  return options.find((opt) => opt.value === value)?.label || "";
};

/**
 * 价格格式化
 */
export const priceFmt = (price: number | null | unknown = 0) => {
  return `￥${Number((price as number) || 0).toFixed(2)}`;
};
